package com.su.bo.process.util

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import freemarker.template.Configuration
import freemarker.template.Template
import freemarker.template.TemplateException
import java.io.IOException
import java.io.StringReader
import java.io.StringWriter

@Suppress("unused")
object JsonToFtl {
    /**
     * @param json json字符串
     * @param ftl  ftl模板字符串
     * @return xml字符串
     */
    @JvmStatic
    @Throws(Exception::class)
    fun toXmlByFtl(json: String?, ftl: String?): String {
        val map = Gson().fromJson<Map<String, Any>>(
            JsonInject.inject(json),
                object : TypeToken<Map<String?, Any?>?>() {}.type)
        val result = StringWriter()
        try {
            Template("strTpl", ftl?.let { StringReader(it) }, Configuration()).process(map, result)
        } catch (ioException: IOException) {
            throw Exception("创建Ftl模板失败")
        } catch (templateException: TemplateException) {
            throw Exception("根据Ftl模板读取数据失败")
        }
        return result.toString()
    }
}